package com.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.example.reggie.common.BaseContext;
import com.example.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * 检查用户是否已经完成登录
 * filterName 过滤器名称
 * urlPatterns 拦截路径
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //    用作路径比较  支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到请求{}", request.getRequestURI());

        // 定义不需要处理的请求路径
        String[] urls = new String[]{"/employee/login", "/employee/logout", "/common/**", "/files/**", "/backend/**", "/front/**", "/favicon.ico"};

        String requestURI = request.getRequestURI();

        // 判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        // 如果不需要处理 直接放行
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        //判断登录状态
        if (request.getSession().getAttribute("employee") != null) {

            Long empId = (Long) request.getSession().getAttribute("employee");

            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;
        }
        //如果未登录则返回未登录结果
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配，检测此次请求是否需要放行
     *
     * @param urls       路径数组
     * @param requestURI 路径
     * @return
     */
    public boolean check(String[] urls, String requestURI) {

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }

        return false;
    }
}
